package me.zhanshi123.lab4.auth;

import me.zhanshi123.lab4.entity.ApiResponse;
import me.zhanshi123.lab4.entity.AuthIdentity;
import me.zhanshi123.lab4.jwt.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class AuthInterceptor implements HandlerInterceptor {

    private void rejectAuthFailed(HttpServletRequest request, HttpServletResponse response, Object handler) {
        try {
            ApiResponse<String> apiResponse = new ApiResponse<>();
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().print(apiResponse.fail("请先登录"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Autowired
    private JwtUtils jwtUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Token");
        if (token == null) {
            rejectAuthFailed(request, response, handler);
            return false;
        }
        AuthIdentity authIdentity = jwtUtils.validateUser(token);
        if (authIdentity == null) {
            rejectAuthFailed(request, response, handler);
            return false;
        }
        request.setAttribute("auth", authIdentity);
        return true;
    }
}
